package com.ys.controller.api.storage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.entity.business.TpAmazonShop;
import com.ys.entity.storage.*;
import com.ys.entity.sys.YsCol;
import com.ys.enume.storage.TccFbaBoxUpEnum;
import com.ys.enume.storage.TccFbaBoxUpItemEnum;
import com.ys.enume.storage.TccFbaPlanEnum;
import com.ys.mapper.storage.TccFbaPlanMapper;
import com.ys.service.storage.FbaInboundApiService;
import com.ys.service.storage.TccFbaBoxUpService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.CheckUtil;
import com.ys.util.DateUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.util.ToolUtil;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import io.swagger.client.model.Item;
import io.swagger.client.model.ListShipmentItemsResponse;
import io.swagger.client.model.Shipment;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * FBA装箱单
 */
@Controller
@RequestMapping("/api/inter/tccFbaBoxUp")
public class ApiInterTccFbaBoxUpController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTccFbaBoxUpController.class);

    @Autowired
    private CommonApiService<TccFbaBoxUp> commonApiService;

    @Autowired
    private CommonApiService<TccFbaBoxUpItem> commonApiByService;

    @Autowired
    private TccFbaBoxUpService tccFbaBoxUpService;

    @Autowired
    private FbaInboundApiService fbaInboundApiService;

    @Autowired
    private CheckUtil checkUtil;

    @Autowired
    private TccFbaPlanMapper tccFbaPlanMapper;


    private final ReentrantLock lock = new ReentrantLock();//同步锁


    //菜单id
    private Long menuId = MenuId.TCC_FbaBoxUp;

    //权限字符
    private final String PERMISSIONS_VIEW = "tccFbaBoxUp:view";
    private final String PERMISSIONS_PRINT_DISTRIBUTION = "tccFbaBoxUp:distributionPrint";//配货清单打印
    private final String PERMISSIONS_PRINT_TAG_GOODS = "tccFbaBoxUp:tagGoodsPrint";//商品标打印
    private final String PERMISSIONS_PRINT_TAG_TRAN = "tccFbaBoxUp:tagTransparentPrint";//透明标打印
    private final String PERMISSIONS_PRINT_TAG_EUR = "tccFbaBoxUp:tagEurPrint";//欧代标打印
    private final String PERMISSIONS_BOX_ROLE_STORAGE = "tccFbaBoxUp:boxRoleStorage";//箱规编辑（仓储）
    private final String PERMISSIONS_BOX_ROLE_BUSINESS = "tccFbaBoxUp:boxRoleBusiness";//箱规编辑（运营）
    private final String PERMISSIONS_FBA_IMPORT = "tccFbaBoxUp:fbaImport";//FBA导入
    private final String PERMISSIONS_PLAN_CANCEL = "tccFbaBoxUp:planCancel";//计划取消
    private final String PERMISSIONS_EXAMINE = "tccFbaBoxUp:examine";//装箱审核
    private final String PERMISSIONS_PLAN_CANCEL_OPERATION = "tccFbaBoxUp:planCancelOperation";//计划取消（运营）
    private final String PERMISSIONS_EDIT_LOGISTICSMETHOD = "tccFbaBoxUp:editLogisticsMethod";//物流服务名称修改
    private final String PERMISSIONS_FBA_IMPORT_BY_BOX = "tccFbaBoxUp:fbaImportByBox";//FBA导入（按箱）
    private final String PERMISSIONS_CHOOSE_IDEA = "tccFbaBoxUp:chooseIdea";//确认方案
    private final String PERMISSIONS_UPDATE_FBA_WAREHOUSE = "tccFbaBoxUp:updateFbaWarehouse";//修改FBA仓库
    private final String PERMISSIONS_UPDATE_FBA_WAREHOUSE_DELIVER = "tccFbaDeliver:updateFbaWarehouse";//修改FBA仓库 - FBA发货单

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TccFbaBoxUp setSeachSqlWithGrid(TccFbaBoxUp cond) throws Exception{

        cond.addField("A.BoxState AS _ys_boxState");//货件状态


        cond
                .addField("FORMAT(A.CreateTime, 'yyyy-MM-dd HH:mm:ss') AS createTimeByStr")//创建时间
                .addField("FORMAT(A.ExamineTime, 'yyyy-MM-dd HH:mm:ss') AS examineTime")//审核时间
                .addLeftJoin("TS_UserChange B ON B.Id = A.ExamineChangeId ")
                    .addField("B.UserId + '/' + B.UserName AS _ys_examineUserName")//审核人
                .addLeftJoin("TS_UserChange C ON C.Id = A.CreateChangeId ")
                    .addField("C.UserId + '/' + C.UserName AS _ys_createUserName")//制单人

                //.addLeftJoin("TCC_FbaBoxRelevance D ON D.BoxUpBid = A.Bid")//关联表
                .addLeftJoin("TCC_FbaBoxUpInfo E ON E.BoxUpBid = A.Bid AND E.SearchIsShow = 1")//装箱单FBA信息表
                    .addField("E.FbaNo AS fbaNo") //FBA编号
                    .addField("E.FbaTrackNo AS fbaTrackNo") //FBA追踪编号
                    .addField("E.FbaWarehouse AS fbaWarehouse") //FBA仓库
                    .addField("E.FbaWarehouseAddr AS fbaWarehouseAddr") //FBA仓库地址
                    .addField("E.FbaAmount AS fbaAmount") //FBA费用

                //获取装箱人
                .addLeftJoin("TS_UserChange G ON G.Id = A.BoxUpChangeId")
                .addField("G.UserId + '/' + G.UserName AS _ys_boxUpUser")//装箱人

                .addLeftJoin("TCC_FbaPlan F ON F.Bid = A.BidFbaPlan")//FBA计划单
                    .addField("F.CreationMethod AS creationMethod")//下单方式(0.手动|1.自动)
                    .addField("F.DeclarationState AS declarationState")//是否报关（1是，0否）
                    .addField("F.DeliverState AS deliverState")//发货计划（1按SKU自动发货，0按箱自动发货）
                    .addField("F.Vgsbm AS vgsbm")//运营公司编码
                    .addField("F.VgsJc AS vgsJc")//运营公司简称
                    .addField("F.ShopName AS shopName")//网店名称
                    .addField("F.ShopId AS shopId")//网店Id
                    .addField("F.Remark AS remarkByFbaPlan")//本单备注
                .addField("F.EvenlyBoxNum AS evenlyBoxNum")//均分箱数

                .addLeftJoin("TCC_FbaLogisticsMethod FC ON FC.sourceBid = F.Bid AND FC.sourceType = 0")
                    .addField("FC.LogsticsWay AS logsticsWay")//物流方式、物流服务名称
                    .addField("FC.Vck AS vckByLogisticsMethod")//发货仓库

                .addLeftJoin("TCC_FbaFeeDetails FD ON FD.sourceBid = F.Bid AND FD.sourceType = 0")
                    .addField("FD.PriceTranPredict AS priceTranPredict")//预估物流费（总）



                ;
        //排序
        cond.setOrderby("A.Bid DESC");
        //权限
        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }






    //处理返回的数据
    public List<Map<String, Object>> setList(List<Map<String, Object>> resDate){
        List<Map<String, Object>> tableDate = new ArrayList<>();
        if(resDate!=null && resDate.size()>0){
            //循环处理数据
            for(int i=0;i<resDate.size();i++) {
                int tagStateGoods = 0;//商品标打印状态
                int tagStateTransparent = 0;//透明标打印状态
                int tagStateEur = 0;//欧代标打印状态

                Map<String, Object> resItem = resDate.get(i);
                if(resItem.get("tagAllGoods")!=null)tagStateGoods = Integer.parseInt(resItem.get("tagAllGoods").toString());//商品标打印状态
                if(resItem.get("tagAllTransparent")!=null)tagStateTransparent = Integer.parseInt(resItem.get("tagAllTransparent").toString());//透明标打印状态
                if(resItem.get("tagAllEur")!=null)tagStateEur = Integer.parseInt(resItem.get("tagAllEur").toString());//欧代标打印状态

                StringBuffer tagStateTxt = new StringBuffer();
                if(tagStateGoods == TccFbaBoxUpItemEnum.TagStateGoods.YES.value){
                    tagStateTxt.append("商品标");
                }
                if(tagStateTransparent == TccFbaBoxUpItemEnum.TagStateTransparent.YES.value){
                    if(tagStateTxt.length()>0){
                        tagStateTxt.append("/");
                    }
                    tagStateTxt.append("透明标");
                }
                if(tagStateEur == TccFbaBoxUpItemEnum.TagStateEur.YES.value){
                    if(tagStateTxt.length()>0){
                        tagStateTxt.append("/");
                    }
                    tagStateTxt.append("欧代标");
                }
                if(tagStateTxt.length()>0){
                    tagStateTxt.append("已打印");
                }
                resItem.put("tagStateTxt",tagStateTxt.length()>0?tagStateTxt:"");
                tableDate.add(resItem);
            }
        }
        return tableDate;
    }



    //查询子列表信息
    @RequestMapping("/searchByRowClick")
    @ResponseBody
    public LayuiTableVoJA searchByRowClick(@ModelAttribute TccFbaBoxUpItem cond,String rowConditions){

        JSONObject chooseParentInfo = JSONObject.parseObject(rowConditions);
        String bid = chooseParentInfo.getString("bid");
        TccFbaBoxUp tccFbaBoxUp = new TccFbaBoxUp().setBid(bid).queryFirst();
        TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(tccFbaBoxUp.getBidFbaPlan()).queryFirst();

        int creationMethod = tccFbaPlan.getCreationMethod();//下单方式(0.手动|1.自动)
        int deliverState = tccFbaPlan.getDeliverState();//发货计划（1按SKU自动发货，0按箱自动发货）

        if(creationMethod ==0 ){//手动
            cond.setBidBoxUp(bid);
        }else{
            cond.setBidBoxUp(bid);
            if(deliverState == 0){//按箱自动发货
                if(chooseParentInfo.get("fbaNo")!=null && !"".equals(chooseParentInfo.get("fbaNo"))){//FBA编号非空=》已审核
                    TccFbaBoxUpInfo tccFbaBoxUpInfo = new TccFbaBoxUpInfo().setFbaNo(chooseParentInfo.get("fbaNo").toString()).queryFirst();
                    cond.addLeftJoin("TCC_FbaBoxDetail D ON D.BoxUpItemId = A.Id")
                            .where("D.FbaBoxUpInfoId = "+tccFbaBoxUpInfo.getId());
                }
            }else {//按SKU自动发货
                cond.addLeftJoin("TCC_FbaBoxRelevance R ON R.BoxUpItemId = A.Id")
                        .where("R.Remark ='"+bid+"'");//去除关联为空的
            }
        }

        cond.addLeftJoin("TCC_FbaPlanItem PS ON PS.Id = A.FbaPlanItemId")
                .addField("PS.CommodityCode AS commodityCode")//商品编码
                .addField("PS.AnnexFile AS annexFile")//透明标签附件
                .addField("PS.CodeGoodsHs AS codeGoodsHs")//海关编码
                .addField("PS.NameGoodsCn AS nameGoodsCn")//商品品名（中文）
                .addField("PS.NameMaterialCn AS nameMaterialCn")//商品材质（中文）
                .addField("CAST(PS.LengthPackage AS varchar(50)) + '*' +  CAST(PS.WidthPackage AS varchar(50)) + '*' +  CAST(PS.HeightPackage AS varchar(50))  goodsSize ")//商品包装尺寸（cm）
                .addField("PS.WeightPackage AS weightPackage")//商品重量（g）
                .addField("PS.CommodityName AS commodityName")//商品名称
                .addField("PS.Sku AS sku")//SKU
                .addField("PS.NumPlanDeliver AS numPlanDeliver")//计划发货数量
                .addField("PS.NumStock AS numStock")//库存可用数量
                .addField("PS.NumApiDeliver AS numApiDeliver")//自动发货数量
                .addField("PS.IsSign AS isSign")//透明标签
                .addField("PS.SignCode AS signCode")//透明标签编码
                .addField("PS.Asin AS asin")//ASIN
                .addField("PS.FnSku AS fnSku")//FNSKU
                .addField("PS.Vck AS vck")//仓库
                .addField("PS.Vkq AS vkq")//库区
                .addField("PS.Vhw AS vhw")//货位

                //按SKU排序
                .setOrderby("PS.Sku ");
        return commonApiByService.searchLay(cond);
    }

    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/searchByWithGrid")
    @ResponseBody
    public LayuiTableVoJA searchByWithGrid(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TccFbaBoxUp cond,String conditions
    ){
        try {
            cond = setSeachSqlWithGrid(cond);
            //查询条件
            String createNameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (createNameLinked != null){
                cond.where("C.UserId LIKE '%" + createNameLinked + "%'" + " OR  C.UserName LIKE '%" + createNameLinked + "%'");
            }
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_examineUserName");//审核人
            if (nameLinked != null){
                cond.where("B.UserId LIKE '%" + nameLinked + "%'" + " OR  B.UserName LIKE '%" + nameLinked + "%'");
            }
            String boxUpUserLinked = ConditionUtil.getConditionValue(conditions, "_ys_boxUpUser");//装箱人
            if (boxUpUserLinked != null){
                cond.where("G.UserId LIKE '%" + boxUpUserLinked + "%'" + " OR  G.UserName LIKE '%" + boxUpUserLinked + "%'");
            }


            ///获取查询页面默认显示的状态
            List<TccFbaBoxUpEnum.BoxState> statusList = TccFbaBoxUpEnum.BoxState.getSearchStatus();

            String orderStatus = ConditionUtil.getConditionValue(conditions, "_ys_boxState");//订单状态
            if (orderStatus == null || "".equals(orderStatus)) {
                //查询的默认状态
                cond.where("A.BoxState IN ("+TccFbaBoxUpEnum.BoxState.getValueSearchByList(statusList)+")");
            }else {
                //-1时显示全部状态
                //非-1时显示选择的对应状态
                if(!"-1".equals(orderStatus)){
                    cond.where("A.BoxState  = "+orderStatus);
                }
            }





            LayuiTableVoJA setList = commonApiService.searchLay(cond);
            //获取
            JSONArray tableVoJAData = setList.getData();

            //转换
            List<Map> resList = JSONArray.parseArray(JSON.toJSONString(tableVoJAData),Map.class);
            List<Map<String, Object>> resListNew = new ArrayList<>();
            resList.forEach(item-> resListNew.add(item));
            //处理数据
            List<Map<String, Object>> resultList = setList(resListNew);
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resultList));
            setList.setData(jsonArray);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }







    /**
     * 查询
     */
//    @RequiresPermissions(PERMISSIONS_VIEW)
//    @RequestMapping("/search")
//    @ResponseBody
//    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
//                                 @ModelAttribute TccFbaBoxUp cond,String conditions
//    ){
//        try {
//            cond = setSeachSql(cond);
//            //查询条件
//            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_examineUserName");//审核人
//            if (nameLinked != null){
//                cond.where("B.UserId LIKE '%" + nameLinked + "%'" + " OR  B.UserName LIKE '%" + nameLinked + "%'");
//            }
//            String boxUpUserLinked = ConditionUtil.getConditionValue(conditions, "_ys_boxUpUser");//装箱人
//            if (boxUpUserLinked != null){
//                cond.where("G.UserId LIKE '%" + boxUpUserLinked + "%'" + " OR  G.UserName LIKE '%" + boxUpUserLinked + "%'");
//            }
//            LayuiTableVoJA setList = commonApiService.searchLay(cond);
//            //获取
//            JSONArray tableVoJAData = setList.getData();
//
//            //转换
//            List<Map> resList = JSONArray.parseArray(JSON.toJSONString(tableVoJAData),Map.class);
//            List<Map<String, Object>> resListNew = new ArrayList<>();
//            resList.forEach(item-> resListNew.add(item));
//            //处理数据
//            List<Map<String, Object>> resultList = setList(resListNew);
//            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resultList));
//            setList.setData(jsonArray);
//
//            return setList;
//        }catch (Exception e){
//            logger.error("查询出错：",e.getMessage(),e);
//            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
//            tableVoJA.setCode(1);
//            tableVoJA.setMsg("查询出错，请稍后重试！");
//            return tableVoJA;
//        }
//    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccFbaBoxUp cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSqlWithGrid(cond);
            String createNameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (createNameLinked != null){
                cond.where("C.UserId LIKE '%" + createNameLinked + "%'" + " OR  C.UserName LIKE '%" + createNameLinked + "%'");
            }
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_examineUserName");//审核人
            if (nameLinked != null){
                cond.where("B.UserId LIKE '%" + nameLinked + "%'" + " OR  B.UserName LIKE '%" + nameLinked + "%'");
            }
            String boxUpUserLinked = ConditionUtil.getConditionValue(conditions, "_ys_boxUpUser");//装箱人
            if (boxUpUserLinked != null){
                cond.where("G.UserId LIKE '%" + boxUpUserLinked + "%'" + " OR  G.UserName LIKE '%" + boxUpUserLinked + "%'");
            }


            ///获取查询页面默认显示的状态
            List<TccFbaBoxUpEnum.BoxState> statusList = TccFbaBoxUpEnum.BoxState.getSearchStatus();

            String orderStatus = ConditionUtil.getConditionValue(conditions, "_ys_boxState");//订单状态
            if (orderStatus == null || "".equals(orderStatus)) {
                //查询的默认状态
                cond.where("A.BoxState IN ("+TccFbaBoxUpEnum.BoxState.getValueSearchByList(statusList)+")");
            }else {
                //-1时显示全部状态
                //非-1时显示选择的对应状态
                if(!"-1".equals(orderStatus)){
                    cond.where("A.BoxState  = "+orderStatus);
                }
            }



            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            listData = setList(listData);
            //处理数据
            ExportExcelUtils<TccFbaBoxUp> util = new ExportExcelUtils<>(new TccFbaBoxUp());
            String toFilePath = util.exportExcel(listData, listField, "FBA装箱单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 配货清单打印
     */
    @RequiresPermissions(PERMISSIONS_PRINT_DISTRIBUTION)
    @RequestMapping("/distributionPrint")
    @ResponseBody
    public R distributionPrint(HttpServletRequest request,String choooseDatas){
        try {
            JSONArray detailJA = JSON.parseArray(choooseDatas);
            //根据装箱单号去重
            List<Map<String, Object>> groupsByJSONArray = ToolUtil.groupsByJSONArray(detailJA,e->e.get("bid")!=null?e.get("bid").toString():"");
            return tccFbaBoxUpService.updateDistributionBid(groupsByJSONArray);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    //保存箱规编辑页信息
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/saveBoxRoleEditInfo")
    @ResponseBody
    public R saveBoxRoleEditInfo(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            return tccFbaBoxUpService.saveBoxRoleEditInfo(params);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    //获取箱规编辑页信息
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/getBoxRoleEditInfo")
    @ResponseBody
    public JSONObject getBoxRoleEditInfo(HttpServletRequest request, String bid){
        JSONObject res = new JSONObject();
        try {
            TccFbaBoxUpBoxRoleEdit tccFbaBoxUpBoxRoleEdit = tccFbaBoxUpService.getBoxRoleEditInfo(bid);
            res.put("code",R.Code.SUCCESS.value);
            res.put("date",tccFbaBoxUpBoxRoleEdit);
            return res;
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            res.put("code",R.Code.FAILED.value);
            res.put("msg","出错");
            return res;
        }
    }


    //FBA导入 RuntimeException
    @RequiresPermissions(PERMISSIONS_FBA_IMPORT)
    @RequestMapping("/fbaImport")
    @ResponseBody
    public R fbaImport(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            if(checkUtil.isNullByObject(params.get("bid"))){
                return R.error("单号为空");
            }
            if(checkUtil.isNullByObject(params.get("fbaNo"))){
                return R.error("FBA编号为空");
            }
            if(checkUtil.isNullByObject(params.get("fbaTrackNo"))){
                return R.error("FBA追踪编号为空");
            }
            return tccFbaBoxUpService.fbaImport(params.get("bid").toString(),params.get("fbaNo").toString(),params.get("fbaTrackNo").toString());
        } catch (RuntimeException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error("访问API出错："+e.getMessage());
        }catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }




    //FBA导入（按箱）
    @RequiresPermissions(PERMISSIONS_FBA_IMPORT_BY_BOX)
    @RequestMapping("/fbaImportByBox")
    @ResponseBody
    public R fbaImportByBox(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {

            return tccFbaBoxUpService.fbaImportByBox(params);
        }catch (RuntimeException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error("访问API出错："+e.getMessage());
        }
        catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    //修改FBA仓库
    @RequiresPermissions(value = {PERMISSIONS_UPDATE_FBA_WAREHOUSE, PERMISSIONS_UPDATE_FBA_WAREHOUSE_DELIVER}, logical = Logical.OR)
    @RequestMapping("/updateFbaWarehouse")
    @ResponseBody
    public R updateFbaWarehouse(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {

            return tccFbaBoxUpService.updateFbaWarehouse(params);
        }catch (RuntimeException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error("出错："+e.getMessage());
        }
        catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }





//    //计划取消
//    @RequiresPermissions(PERMISSIONS_PLAN_CANCEL)
//    @RequestMapping("/planCancel")
//    @ResponseBody
//    public R planCancel(HttpServletRequest request, @RequestParam Map<String, Object> params){
//        try {
//            //获取数据
//            String choooseDatas = params.get("choooseDatas").toString();
//            //根据计划单号去重
//            List<Map<String, Object>> detailList = ToolUtil.groupsByJSONArray(JSON.parseArray(choooseDatas),e->e.get("bidFbaPlan").toString());
//            int doCount = 0;
//            StringBuilder resMsg = new StringBuilder();
//            for (int i = 0; i < detailList.size(); i++) {
//                Map<String, Object> info = detailList.get(i);
//                //处理
//                R res = tccFbaBoxUpService.planCancel(info.get("bidFbaPlan").toString());
//                if(res.getCode()==0){
//                    doCount ++;
//                }else{
//                    resMsg.append((info.get("bidFbaPlan")!=null?"计划单号："+info.get("bidFbaPlan"):"")+"；")
//                            .append(res.getMsg())
//                            .append("</br>");
//                }
//            }
//            resMsg.append("成功计划取消").append(doCount).append("条数据</br>").append(resMsg);
//            return R.ok(resMsg.toString());
//
//        } catch (Exception e) {
//            logger.error("出错：",e.getMessage(),e);
//            return R.error(e.getCause().getMessage());
//        }
//    }




//    //计划取消(运营)
//    @RequiresPermissions(PERMISSIONS_PLAN_CANCEL_OPERATION)
//    @RequestMapping("/planCancelByOperation")
//    @ResponseBody
//    public R planCancelByOperation(HttpServletRequest request, @RequestParam Map<String, Object> params){
//        try {
//            //获取数据
//            String choooseDatas = params.get("choooseDatas").toString();
//            //根据计划单号去重
//            List<Map<String, Object>> detailList = ToolUtil.groupsByJSONArray(JSON.parseArray(choooseDatas),e->e.get("bidFbaPlan").toString());
//            int doCount = 0;
//            StringBuilder resMsg = new StringBuilder();
//            for (int i = 0; i < detailList.size(); i++) {
//                Map<String, Object> info = detailList.get(i);
//                //处理
//                R res = tccFbaBoxUpService.planCancelByOperation(info.get("bidFbaPlan").toString());
//                if(res.getCode()==0){
//                    doCount ++;
//                }else{
//                    resMsg.append((info.get("bidFbaPlan")!=null?"计划单号："+info.get("bidFbaPlan"):"")+"；")
//                            .append(res.getMsg())
//                            .append("</br>");
//                }
//            }
//            resMsg.append("成功计划取消").append(doCount).append("条数据</br>").append(resMsg);
//            return R.ok(resMsg.toString());
//
//        } catch (Exception e) {
//            logger.error("出错：",e.getMessage(),e);
//            return R.error(e.getCause().getMessage());
//        }
//    }





    //装箱审核 - 手动、按SKU自动发货
    @RequiresPermissions(PERMISSIONS_EXAMINE)
    @RequestMapping("/examine")
    @ResponseBody
    public R examine(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //获取数据
            String bidFbaPlan = params.get("bidFbaPlan").toString();
            String bid = params.get("bid").toString();
            TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(bidFbaPlan).queryFirst();
            if(tccFbaPlan.getCreationMethod()==0 ){//手动
                //审核
                return tccFbaBoxUpService.examineByHand(bidFbaPlan);
            }
            //自动 && 按SKU自动发货
            if(tccFbaPlan.getCreationMethod()==1 && tccFbaPlan.getDeliverState()==1){
                return R.error("按SKU自动发货暂未开放");
                /*
                //上传箱规信息
                R uploadBoxRoleRes = tccFbaBoxUpService.uploadPackingInfo(bid);
                if(uploadBoxRoleRes.getCode().equals(R.Code.FAILED.value)){
                    return uploadBoxRoleRes;
                }
                //审核
                return tccFbaBoxUpService.examine(bidFbaPlan);
                 */
            }
            return R.error("状态有误");

        } catch (IllegalArgumentException e) {
            //logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 获取货件预览信息
     * @param bid 装箱单号
     * @return 预览信息
     */
    @RequestMapping("/getShipmentList")
    @ResponseBody
    public R getShipmentList(String bid){
        TccFbaBoxUp tccFbaBoxUp = new TccFbaBoxUp().setBid(bid).queryFirst();
        if(tccFbaBoxUp==null){
            return R.error("装箱单号传参有误！");
        }

        lock.lock(); // 加锁

        TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(tccFbaBoxUp.getBidFbaPlan()).queryFirst();
        try {


            //是否需要重新获取方案
            boolean isRetGetApi = false;
            //是否处于正在获取方案中
            boolean isGetApiing = false;

            if(checkUtil.isNullByObject(tccFbaBoxUp.getPlacementOptionId()) && //方案id是空
                    !tccFbaBoxUp.getBoxState().equals(TccFbaBoxUpEnum.BoxState.YES_CANCEL.value) //非取消
            ){
                isRetGetApi = true;
                //是否处于获取中的状态
                if(tccFbaPlan.getApiGetStatus()==2 //获取中
                    && tccFbaPlan.getBoxRoleEditNo() - tccFbaPlan.getGenerateNo()==0 //箱规编辑次数标识 与 当前API获取对应箱规编辑次数标识 一致
                    && tccFbaPlan.getApiGetTime() !=null
                     && DateUtil.getMinutesSpace(tccFbaPlan.getApiGetTime(),new Date())-10<=0 //获取时间不超过10分钟
                ){
                    isRetGetApi = false;
                    isGetApiing = true;
                }
                if(tccFbaPlan.getApiGetStatus().equals(TccFbaPlanEnum.ApiGetStatus.SUCCESS.value) //成功获取
                        && tccFbaPlan.getBoxRoleEditNo() - tccFbaPlan.getGenerateNo()==0 //箱规编辑次数标识 与 当前API获取对应箱规编辑次数标识 一致
                ){
                    isRetGetApi = false;
                }
            }


            //是否已选择方案
            if(isRetGetApi){

                //如果尚未选择方案
                //删除保存的API预览信息
                //tccFbaBoxUpService.delBoxUpAutoAndBoxApiPreviewInfo(tccFbaBoxUp.getBidFbaPlan(),tccFbaPlan.);

                //修改计划单相关状态
                tccFbaPlan.setAuditingTime(new Date()); //API获取时间
                tccFbaPlan.setGenerateNo(tccFbaPlan.getBoxRoleEditNo());//当前API获取对应箱规编辑次数标识
                tccFbaPlan.setApiGetStatus(TccFbaPlanEnum.ApiGetStatus.ING.value);//API获取成功与否标识
                tccFbaPlanMapper.update(tccFbaPlan);

                lock.unlock(); // 释放锁

                //未选择方案
                //上传箱规信息
                R uploadBoxRoleRes = tccFbaBoxUpService.uploadPackingInfo(bid);
                if(uploadBoxRoleRes.getCode().equals(R.Code.FAILED.value)){//失败
                    if(new TccFbaPlan().setBid(tccFbaPlan.getBid()).queryFirst().getGenerateNo()-tccFbaPlan.getGenerateNo()==0){
                        tccFbaPlan.setApiGetStatus(TccFbaPlanEnum.ApiGetStatus.FAIL.value);//API获取成功与否标识
                        tccFbaPlanMapper.update(tccFbaPlan);
                    }
                    return uploadBoxRoleRes;
                }
                //未，通过api获取预览信息
                R getRes = fbaInboundApiService.generatePlacementOptions(tccFbaBoxUp,tccFbaPlan.getGenerateNo());

                if(getRes.getCode().equals(R.Code.FAILED.value)){//失败
                    if(new TccFbaPlan().setBid(tccFbaPlan.getBid()).queryFirst().getGenerateNo()-tccFbaPlan.getGenerateNo()==0){
                        tccFbaPlan.setApiGetStatus(TccFbaPlanEnum.ApiGetStatus.FAIL.value);//API获取成功与否标识
                        tccFbaPlanMapper.update(tccFbaPlan);
                    }
                    return getRes;
                }else {
                    if(new TccFbaPlan().setBid(tccFbaPlan.getBid()).queryFirst().getGenerateNo()-tccFbaPlan.getGenerateNo()==0){
                        tccFbaPlan.setApiGetStatus(TccFbaPlanEnum.ApiGetStatus.SUCCESS.value);//API获取成功与否标识
                        tccFbaPlanMapper.update(tccFbaPlan);
                    }
                }
            }else{
                lock.unlock(); // 释放锁
            }

            //return fbaInboundApiService.searchFlow(bid);
            /*
            List<TccFbaShipmentPreview> resList = new ArrayList<>();

            //遍历预览信息，填入返回值
            for(int i = 0 ;i<jsonResultList.size() ;i++){
                TccFbaInboundApiLog tccFbaInboundApiLog = jsonResultList.get(i);

                TccFbaShipmentPreview tccFbaShipmentPreview = new TccFbaShipmentPreview();
                tccFbaShipmentPreview.setRadioNum(i+1);
                tccFbaShipmentPreview.setShippingSolution("aaaa");
                tccFbaShipmentPreview.setFee(BigDecimal.ZERO);
                tccFbaShipmentPreview.setFbaName("weweqweqweq");
                tccFbaShipmentPreview.setPlacementOptionId("asdad");
                tccFbaShipmentPreview.setShipmentId("bnvnbhg");
                tccFbaShipmentPreview.setWarehouseId("popopmk");
                resList.add(tccFbaShipmentPreview);
            }
             */
            if(isGetApiing){//正在获取中
                return R.error("系统正在获取方案中，请稍后");
            }else {
                return getShipmentPreview(tccFbaBoxUp.getBidFbaPlan());
            }


        } catch (Exception e) {
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            if(new TccFbaPlan().setBid(tccFbaPlan.getBid()).queryFirst().getGenerateNo()-tccFbaPlan.getGenerateNo()==0){
                tccFbaPlan.setApiGetStatus(TccFbaPlanEnum.ApiGetStatus.FAIL.value);//API获取成功与否标识
                tccFbaPlanMapper.update(tccFbaPlan);
            }
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } finally {
            try {
                lock.unlock(); // 确保释放锁
            }catch (Exception e){

            }
        }
    }


    //FbaInboundApiService.searchFlow
    public R getShipmentPreview(String planBid){
        TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(planBid).queryFirst();
        //正式切换代码
        List<TccFbaShipmentPreview> tccFbaShipmentPreviewList = new ArrayList<>();

        TccFbaInboundApiLog tccFbaInboundApiLog = new TccFbaInboundApiLog()
                //.setPid(tccFbaPlan.getId().toString())
                .setBid(tccFbaPlan.getBid())
                .setType("listPlacementOptions-"+tccFbaPlan.getGenerateNo())
                .queryFirst();
        if (tccFbaInboundApiLog != null){
            JSONObject resultJO = JSON.parseObject(tccFbaInboundApiLog.getJsonResult());
            JSONArray conditionJA = JSON.parseArray(resultJO.get("placementOptions").toString());
            BigDecimal fee = BigDecimal.ZERO;
            for (int i = 0; i < conditionJA.size(); i++) {
                JSONObject JO = conditionJA.getJSONObject(i);
                JSONArray shipmentIds = JSON.parseArray(JO.get("shipmentIds").toString());
                JSONArray fees = JSON.parseArray(JO.get("fees").toString());
                //查询货件详情
                for (int j = 0; j < shipmentIds.size(); j++) {
                    String  shipmentId = shipmentIds.get(j).toString();
                    TccFbaInboundApiLog shipmentLog = new TccFbaInboundApiLog()
                            .setPid(shipmentId)
                            .setBid(tccFbaPlan.getBid())
                            .setType("getShipment-"+tccFbaPlan.getGenerateNo())
                            .queryFirst();
                    if (shipmentLog == null){
                        continue;
                    }
                    Shipment shipment = JSON.parseObject(shipmentLog.getJsonResult(), Shipment.class);

                    TccFbaShipmentPreview tccFbaShipmentPreview = new TccFbaShipmentPreview();
                    tccFbaShipmentPreview.setRadioNum(i);
                    tccFbaShipmentPreview.setShippingSolution(shipmentIds.size() + "个货件");
                    if (fees != null) {
                        for (int k = 0; k < fees.size(); k++) {
                            JSONObject feeJs = fees.getJSONObject(k);
                            if (feeJs.get("target").equals("Placement Services")){
                                JSONObject feeValue = JSON.parseObject(feeJs.get("value").toString());
                                if (feeValue.size() != 0){
                                    fee = new BigDecimal(feeValue.get("amount").toString());
                                }
                            }
                        }
                    }
//                    tccFbaShipmentPreview.setFee(fee.compareTo(BigDecimal.ZERO)==0?"":fee);
                    tccFbaShipmentPreview.setFbaName(shipment.getName());
                    tccFbaShipmentPreview.setPlacementOptionId(shipment.getPlacementOptionId());
                    tccFbaShipmentPreview.setShipmentId(shipment.getShipmentId());
                    tccFbaShipmentPreview.setWarehouseId(shipment.getDestination().getWarehouseId());
                    tccFbaShipmentPreviewList.add(tccFbaShipmentPreview);
                }
            }
        }

        return R.ok(tccFbaShipmentPreviewList);
    }

    /**
     * 获取货件预览详情信息
     * @param bid 装箱单号
     * @param shipmentId 货件id
     * @return 货件预览详情信息
     */
    @RequestMapping("/getShipmentListDetail")
    @ResponseBody
    public R getShipmentListDetail(String bid,String shipmentId){
        try {
            //return fbaInboundApiService.searchFlowDetail(bid,shipmentId);

            TccFbaBoxUp  tccFbaBoxUp = new TccFbaBoxUp().setBid(bid).queryFirst();

            List<TccFbaPlanItem> tccFbaPlanItemListDatail = new ArrayList<>();
            ListShipmentItemsResponse listShipmentItemsResponse;
            List<TccFbaPlanItem> tccFbaPlanItemListNew;

            try {
                TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(tccFbaBoxUp.getBidFbaPlan()).queryFirst();

                TccFbaInboundApiLog tccFbaInboundApiLog = new TccFbaInboundApiLog()
                        .setPid(shipmentId)
                        .setBid(tccFbaBoxUp.getBidFbaPlan())
                        .setType("listShipmentItems-"+tccFbaPlan.getGenerateNo())
                        .queryFirst();

                listShipmentItemsResponse = JSON.parseObject(tccFbaInboundApiLog.getJsonResult(), ListShipmentItemsResponse.class);
                List<TccFbaPlanItem> tccFbaPlanItemList = new TccFbaPlanItem().setBidFbaPlan(tccFbaPlan.getBid()).queryList();

                for (Item item : listShipmentItemsResponse.getItems()){
                    //查询出来商品信息
                    tccFbaPlanItemListNew = tccFbaPlanItemList.stream().filter(tccFbaPlanItem -> item.getAsin().equals(tccFbaPlanItem.getAsin())
                            && item.getFnsku().equals(tccFbaPlanItem.getFnSku())
                            && item.getMsku().equals(tccFbaPlanItem.getSku()))
                            .collect(Collectors.toList());

                    if (tccFbaPlanItemListNew.size() !=0){
                        TccFbaPlanItem tccFbaPlanItem = tccFbaPlanItemListNew.get(0);
                        tccFbaPlanItem.setNumPlanDeliver(item.getQuantity());
                        tccFbaPlanItemListDatail.add(tccFbaPlanItem);
                    }
                }

            }catch (Exception e){
                logger.error("货件预览详情失败!:" ,e.getMessage(),e);
                return R.error(e.getMessage());
            }

            return R.ok(tccFbaPlanItemListDatail);



        } catch (Exception e) {
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }



    /**
     * 计划审核验证-按箱自动发货
     */
    @RequiresPermissions(PERMISSIONS_EXAMINE)
    @PostMapping("/examineAutoByCheck")
    @ResponseBody
    public R examineAutoByCheck(HttpServletRequest request,@RequestParam Map<String, Object> params){
        try {
            //获取数据
            String bidFbaPlan = params.get("bidFbaPlan").toString();
            //验证信息状态是否可以审核
            R checkStatus = tccFbaBoxUpService.examineBeforeCheck(bidFbaPlan);
            if(checkStatus.getCode().equals(R.Code.FAILED.value)){//失败
                return checkStatus;
            }
            //验证采购价
            R checkAmount = tccFbaBoxUpService.checkPurchaseAmount(bidFbaPlan);
            if(checkAmount.getCode().equals(R.Code.FAILED.value)){//失败
                return R.ok(checkAmount.getMsg());
            }
            return R.ok("pass");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }



    /**
     * 方案选择验证-按箱自动发货
     */
    @RequiresPermissions(PERMISSIONS_CHOOSE_IDEA)
    @PostMapping("/chooseIdeaByCheck")
    @ResponseBody
    public R chooseIdeaByCheck(HttpServletRequest request,@RequestParam Map<String, Object> params){
        try {
            //获取数据
            String bidFbaPlan = params.get("bidFbaPlan").toString();
            //验证箱规
            List<TccFbaBoxUp> fbaBoxUpList = new TccFbaBoxUp().setBidFbaPlan(bidFbaPlan).queryList();
            //验证
            if(fbaBoxUpList!=null && fbaBoxUpList.size()>0) {
                for (TccFbaBoxUp tccFbaBoxUp : fbaBoxUpList) {
                    int countByBox = new TccFbaBox().setBidBoxUp(tccFbaBoxUp.getBid()).count();
                    if(countByBox<=0){
                        return R.error("装箱单："+tccFbaBoxUp.getBid()+"还未进行箱规编辑；");
                    }
                }
            }
            return R.ok("pass");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 确认选择方案-按箱自动发货
     * params：
     *      {
     *          dataPost 选择的方案JSON
     *          bid 装箱单号
     *      }
     *
     */
    @RequiresPermissions(PERMISSIONS_CHOOSE_IDEA)
    @PostMapping("/yesChooseIdea")
    @ResponseBody
    public R yesChooseIdea(HttpServletRequest request,@RequestParam Map<String, Object> params){
        try {
            //确认选择方案
            return tccFbaBoxUpService.yesChooseIdea(params);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(e.getMessage());
        }
    }




    /**
     * 计划审核-按箱自动发货
     * params：
     *      {
     *          dataPost 选择的方案JSON
     *          bid 装箱单号
     *          isReCountPurchaseAmount 是否重新计算采购价
     *      }
     *
     */
    @RequiresPermissions(PERMISSIONS_EXAMINE)
    @PostMapping("/examineByAuto")
    @ResponseBody
    public R examineByAuto(HttpServletRequest request,@RequestParam Map<String, Object> params){
        try {
            //审核
            return tccFbaBoxUpService.doExamineByAutoAndBox(params);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(e.getMessage());
        }
    }






    /**
     * 物流服务名称修改
     */
//    @RequiresPermissions(PERMISSIONS_EDIT_LOGISTICSMETHOD)
//    @PostMapping("/editLogisticsMethod")
//    @ResponseBody
//    public R editLogisticsMethod(HttpServletRequest request,@RequestParam Map<String, Object> params){
//        try {
//            if(checkUtil.isNullByObject(params.get("bid"))){
//                return R.error("单号为空");
//            }
//            if(checkUtil.isNullByObject(params.get("logisticsMethodId"))){
//                return R.error("物流服务参数有误");
//            }
//            return tccFbaBoxUpService.editLogisticsMethodId(params.get("bid").toString(),Long.parseLong(params.get("logisticsMethodId").toString()));
//        } catch (Exception e) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            logger.error("出错：",e.getMessage(),e);
//            return R.error(e.getMessage());
//        }
//    }


    /**
     * 获取打印标签页的列表信息
     *  bid //单号
     * 	printType //打印类型：0商品标、1透明标、2欧代标
     */

    @PostMapping("/printTypeSearchList")
    @ResponseBody
    public R printTypeSearchList(HttpServletRequest request,@RequestParam Map<String, Object> params){

        try {
            if(checkUtil.isNullByObject(params.get("bid"))){
                return R.error("单号为空");
            }
            if(checkUtil.isNullByObject(params.get("printType"))){
                return R.error("打印类型为空");
            }
            return tccFbaBoxUpService.printTypeSearchList(params.get("bid").toString(),Integer.parseInt(params.get("printType").toString()));
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }


    /**
     * 打印欧代标打印
     *  bid 单号
     */

    @PostMapping("/europeanStandardPrint")
    @ResponseBody
    public R europeanStandardPrint(HttpServletRequest request,@RequestParam Map<String, Object> params) {
        try {
            return tccFbaBoxUpService.europeanStandardPrint(params);
        } catch (Exception e) {
            logger.error("出错：", e.getMessage(), e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 修改对应标签状态
     */
    @PostMapping("/updateTagState")
    @ResponseBody
    public R updateTagState(HttpServletRequest request,@RequestParam Map<String, Object> params){

        try {
            if(checkUtil.isNullByObject(params.get("bid"))){
                return R.error("单号为空");
            }
            if(checkUtil.isNullByObject(params.get("printType"))){
                return R.error("打印类型为空");
            }
            return tccFbaBoxUpService.updateTagState(params);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }


    /**
     * 打印商品标
     *  bid 单号
     */
    @PostMapping("/getGoodsPrintInfo")
    @ResponseBody
    public R getGoodsPrintInfo(HttpServletRequest request,@RequestParam Map<String, Object> params) {
        try {
            return tccFbaBoxUpService.getGoodsPrintInfo(params);
        } catch (Exception e) {
            logger.error("出错：", e.getMessage(), e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 方案选择验证-按箱自动发货
     */
    @PostMapping("/ifLabels")
    @ResponseBody
    public R ifLabels(HttpServletRequest request,@RequestParam String bid){
        try {
            //验证箱规
            TccFbaBoxUp fbaBoxUp = new TccFbaBoxUp().setBid(bid).queryFirst();
            //验证
            if(fbaBoxUp!=null) {
                TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(fbaBoxUp.getBidFbaPlan()).queryFirst();
                TpAmazonShop tpAmazonShop = new TpAmazonShop().setId(tccFbaPlan.getShopId()).queryFirst();
                //欧代标
                if (tpAmazonShop.getEuStatus() == 1){
                    if (fbaBoxUp.getTagAllEur() != 1){
                        return R.error("欧代标未打印,不允许箱规编辑!");
                    }
                }
                //透明标
                if (fbaBoxUp.getTagAllTransparent() != 1){
                    return R.error("透明标未打印,不允许箱规编辑!");
                }

            }
            return R.ok("pass");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    }
